﻿using System.Collections.Generic;
using System.Linq;

using Game.Common;
using Game.Map;
using Game.Map.Extensions;
using Game.PathFinder;

namespace Game.Ai.Internal
{
    static class AiUtil
    {
        struct Pair
        {
            public IMapField Field;
            public double Distance;
        }
        
        public static IMapField FindOther(AiController ai)
        {
            var target = ai.GameMap.FindItem(ai.Vehicle);
            GameDebug.Assert(target != null);
            
            var list = new List<Pair>();
            foreach (var field in ai.GameMapView.ViewFields) 
            {
                if (!field.IsVisible) 
                {
                    continue;
                }
                
                if (field.VehicleX().Vehicle == null) 
                {
                    continue;
                }
                
                if (field.VehicleX().Vehicle.Owner == AiPlayer.Player) 
                {
                    continue;
                }

                var p = new Pair
                            {
                                Field = field, 
                                Distance = CalcDistance(ai.GameMap, field, target)
                            };
                list.Add(p);
            }
            
            IMapField other = null;
            if (list.Count > 0)
            {
                var smallestDistance = list.Min(p => p.Distance);
                var pair = ( 
                    from p in list 
                    where p.Distance == smallestDistance 
                    select p).First();
                other = pair.Field;
            }
            
            return other;
        }
        
        static double CalcDistance(IGameMap map, IMapField field1, IMapField field2)
        {
            var finder = FinderFactory.Create(map, field1, field2);
            var path = finder.Find();
            if (path == null)
            {
                return 99;
            }

            return path.CalcTerrainCost(map);
        }
        
    }
}
